#!/bin/bash
#
# Copyright 2007 Kaio Rafael de Souza Barbosa
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# ---------------------------------------------------------
# Este script cria repositorio, muda a permissao para o apache
# poder ler e escrever os commits realizados pelos usuarios
#
# Para mais detalhes do subversion acesse: 
# http://svnbook.red-bean.com/nightly/pt_BR/svn-book.html#svn.serverconfig.httpd
# http://svnbook.red-bean.com/nightly/pt_BR/svn-book.html#svn.reposadmin


# Variables

apache_user=www-data # usuario do apache
apache_group=www-data # grupo do usuario do apache
apache_htpass_cmd=/usr/bin/htpasswd # comando do apache
svn_root_home=/home/kaio/temp/web-svn # diretorio que armazena todos os repositorios do subversion
svn_adm_cmd=/usr/bin/svnadmin # comando do svnadmin
svn_pass_file=/home/kaio/temp/senha # arquivo de senha dos usuarios do subversion
svn_access_dir=/home/kaio/temp/projetos # diretorio com as permissoes do subversion
svn_tmp=/tmp/repos.$$ # arquivo temporario
svn_web_page=/svn # endereco web que ficara o repositorio http://server/svn/nome_repositorio
nome_empresa="Free Software Foundation" # Nome da sua empresa
auto_passwd=`od /dev/urandom | head -1 | awk '{print $2}'` # senha gerada pelo /dev/random
#auto_passwd=`mkpasswd *3$%#er` # senha gerada pelo mkpasswd

version=0.3.2.beta

# Functions

#
# Funcao que imprime o ajuda
#
usage(){
	echo
	echo "usage: $(basename $0) [opcoes]"
	echo
	echo "Opcoes:"
	echo " "
	echo -e "--create -t (default|ldap)\t : Cria um repositorio"
	echo -e "--adduser user\t		 : Adiciona um usuario"
	echo -e "--adduser-gen user\t	 : Mesmo que --adduser, porem o sistema gera uma senha"
	echo -e "--help\t			 : Imprime esta ajuda"
	echo -e "--version\t		 : Imprime versao do $0"
	echo " "
}

#
# Funcao para criar um repositorio 
#
create_svn(){
template=$1 #  por padrao vai utilizar o apache

	echo -n "Entre com o nome do repositorio a ser criado: "
	read svn_repos

	# verifica se o repositorio ja existe

	if [ -d ${svn_root_home}/${svn_repos} ];then
		echo "Repositorio ${svn_repos} ja existe"
		exit 1

		else

		if `${svn_adm_cmd} create ${svn_root_home}/${svn_repos}` ; then
			echo "Repositorio ${svn_repos}, criado com sucesso!!"
			else
			echo "Erro na criacao do repositorio  ${svn_repos}"
			exit 1
		fi
	fi

#
# Mudando permissoes DAV, LOCK e DB
#

echo "Mudando as permissoes de dav, lock e db"

chmod g+w  ${svn_root_home}/${svn_repos}/dav \
 ${svn_root_home}/${svn_repos}/locks  ${svn_root_home}/${svn_repos}/db

chmod g+s  ${svn_root_home}/${svn_repos}/dav \
 ${svn_root_home}/${svn_repos}/locks  ${svn_root_home}/${svn_repos}/db

chown -R ${apache_user}:${apache_group} ${svn_root_home}/${svn_repos}/dav
chown -R ${apache_user}:${apache_group} ${svn_root_home}/${svn_repos}/locks
chown -R ${apache_user}:${apache_group} ${svn_root_home}/${svn_repos}/db

#
# Saida das permissoes 
#

cat << EOF > ${svn_access_dir}/${svn_repos}
[groups]
develop =
cm = 

[/]
@develop = r

EOF

# 
# Template do Apache 
#

if [ "$template" = default ];then

cat << EOF > $svn_tmp
###########################
#   Projeto ${svn_repos}
###########################
<Location ${svn_web_page}/${svn_repos}>
   DAV svn
   SVNPath ${svn_root_home}/${svn_repos}
   AuthType Basic
   AuthName "${svn_repos} em ${nome_empresa} "
   AuthUserFile ${svn_pass_file}
   AuthzSVNAccessFile ${svn_access_dir}/${svn_repos}
   Require valid-user
   Allow from all
</Location>
EOF

# 
# Template do LDAP
#

elif [ "$template" = "ldap" ]; then

cat << EOF > $svn_tmp
###########################
#   Projeto ${svn_repos}
###########################
<Location ${svn_web_page}/${svn_repos}>
   DAV svn
   SVNPath ${svn_root_home}/${svn_repos}
   AuthType Basic
   AuthName "${svn_repos} em ${nome_empresa} "
   AuthBasicProvider ldap
   AuthzLDAPAuthoritative on
   AuthLDAPURL ldap://IP_DO_SERVIDOR:3268/DC=mysvnadmin,DC=org?samAccountName?sub?(objectCategory=*)
   AuthLDAPBindDN "CN=mysvnuser,CN=Users,DC=mysvnadmin,DC=org"
   AuthLDAPBindPassword mysvnpassword
   AuthzSVNAccessFile ${svn_access_dir}/${svn_repos}
#   SVNIndexXSLT "/svnindex.xsl"
   Require ldap-user
   Allow from all
</Location>
EOF

fi

echo "Adicione as linhas abaixo no arquivo do apache"
echo " "
cat  $svn_tmp
}

#
# Procura o usuario na base de senha
#
search_svnuser() {
	if [ -z $1 ]; then
		echo "Digite o nome do usuario"
 	elif [ "$(cut -f1 -d: ${svn_pass_file} | grep "\<${1}\>" )" = $1 ]; then
		echo "Usuario $1, ja existe"
		exit 1
	fi

}

#
# Adiciona o usuario
#
adduser_svn(){
	search_svnuser $1
	echo "Criando usuario: $1"
	${apache_htpass_cmd} ${svn_pass_file} $1
	
}

#
# Adiciona um usuario SVN com senha gerada adduser_genpass()
#
adduser_genpass(){
	search_svnuser $1
	echo "Criando usuario: $1"
	${apache_htpass_cmd} -b ${svn_pass_file} $1 ${auto_passwd}
	echo "A Senha para $1: ${auto_passwd}"
}

#
# Validando as variaveis do Sistema
#

if [ ! -f ${svn_pass_file} ];then
	echo 
	echo "O arquivo: ${svn_pass_file} nao existe"
	echo "Voce deve mudar a variavel \${svn_pass_file}"
	echo 
	exit 1
fi

if [ ! -f ${apache_htpass_cmd} ];then
	echo 
	echo "O arquivo:  ${apache_htpass_cmd} nao existe"
	echo "Voce deve mudar a variavel \${apache_htpass_cmd}"
	echo 
	exit 1
fi

if [ ! -d ${svn_access_dir} ] ;then
	echo 
	echo "O diretorio: ${svn_access_dir} nao existe"
	echo "Voce deve mudar a variavel \${svn_access_dir}"
	echo 
	exit 1
fi

if [ ! -d ${svn_root_home} ] ;then
	echo 
	echo "O diretorio: ${svn_root_home} nao existe"
	echo "Voce deve mudar a variavel \${svn_root_home}"
	echo 
	exit 1
fi

# 
# Programa Principal
#
if [ $(id -u) -eq 0 ];then
	if [ $# -eq 0 ]; then
		usage
		exit 1
		else

		case $1 in 
		--create) 
		if [ "$1" = "--create" -a  "$3" = "default" ];then
		 create_svn default
	  	elif [ "$1" = "--create" -a  "$3" = "ldap" ];then
		  create_svn ldap
		fi ;;

		--adduser) 
			if [ -z $2 ];then
			  usage
			  exit 1
			else
			  adduser_svn $2
			fi ;;
		--adduser-gen) 
			if [ -z $2 ];then
			  usage
			  exit 1
			else
			  adduser_genpass $2;
			fi ;;
		--help) usage;;
		--version)
			echo "$0 $version";;
		*) echo "Parametro $1, desconhecido";;
		esac
	fi
	else
	echo "Precisa permissao de Root"
	exit 1
fi
